import 'dart:io';

import 'package:demo/common/net/http_util.dart';
import 'package:recase/recase.dart';

/// 按json生成语言文件 例如:
///  String jsonStr = '''
/// {
///   "zh_cn": {
///     "coins": "金币",
///     "set_privacy": "隐私政策\\n fsfdsafdaf",
///     "set_service": "服务条款"
///    },
/// "en_us": {
///     "coins": "Coins",
///     "set_privacy": "aa",
///     "set_service": "bb"
///    }
/// }
/// ''';
Future<void> main() async {
  final String url = "https://p.djszxm.online/translation/v1.json";
  final String path = 'lib/common/i18n';

  var response = await HttpUtil().get(url: url, addHeaders: false, addSign: false, asHttpResponseData: false);

  Map<String, dynamic> data = response;

  // 创建输出目录
  final outputDir = Directory(path);
  final lanDir = Directory("$path/lan");

  lanDir.createSync(recursive: true);

  // 生成所有键的集合
  final allKeys = _extractAllKeys(data);

  // 生成主键文件
  _generateKeysFile(allKeys, outputDir);

  // 生成配置文件
  _generateConfigFile(data.keys.toList(), outputDir);

  // 生成各语言文件
  _generateLanguageFiles(data, allKeys, lanDir);

  print('国际化文件生成成功: ${outputDir.path}');
}

Set<String> _extractAllKeys(Map<String, dynamic> data) {
  final allKeys = <String>{};
  for (final map in data.values) {
    if (map is Map<String, dynamic>) {
      allKeys.addAll(map.keys);
    }
  }
  return allKeys;
}

void _generateKeysFile(Set<String> allKeys, Directory outputDir) {
  final buffer = StringBuffer();

  buffer.writeln('class LanKeys {');

  // 添加键常量
  for (final key in allKeys) {
    final camelCase = key.camelCase;
    buffer.writeln('  static const String $camelCase = \'$key\';');
  }

  buffer.writeln('}');

  // 写入文件
  File('${outputDir.path}/lan_keys.dart').writeAsStringSync(buffer.toString());
}

void _generateConfigFile(List<String> langCodes, Directory outputDir) {
  final buffer = StringBuffer()
    ..writeln('import \'dart:ui\';')
    ..writeln();

  // 添加导入语句
  for (final lang in langCodes) {
    buffer.writeln('import \'lan/lan_${lang.toLowerCase()}.dart\';');
  }

  buffer
    ..writeln()
    ..writeln('class LanConfig {');

  // 支持的语言列表
  buffer
    ..writeln('  /// 支持的语言')
    ..writeln('  static const List<Locale> supportedLocales = [');

  for (final lang in langCodes) {
    final parts = lang.split('_');
    if (parts.length == 2) {
      buffer.writeln('    Locale(\'${parts[0]}\', \'${parts[1].toUpperCase()}\'),');
    }
  }

  buffer.writeln('  ];');

  // 语言映射
  buffer
    ..writeln()
    ..writeln('  /// 语言映射表')
    ..writeln('  static const Map<String, Map<String, String>> languageMap = {');

  for (final lang in langCodes) {
    final parts = lang.split('_');
    if (parts.length == 2) {
      final langKey = parts[0];
      final mapName = '$langKey${parts[1].pascalCase}';
      buffer.writeln('    \'$langKey\': $mapName,');
    }
  }

  buffer.writeln('  };');
  buffer.writeln('}');

  // 写入配置文件
  File('${outputDir.path}/lan_config.dart').writeAsStringSync(buffer.toString());
}

void _generateLanguageFiles(Map<String, dynamic> data, Set<String> allKeys, Directory outputDir) {
  for (final entry in data.entries) {
    final lang = entry.key;
    final map = entry.value as Map<String, dynamic>;
    final parts = lang.split('_');

    if (parts.length != 2) continue;

    final buffer = StringBuffer()
      ..writeln('import \'../lan_keys.dart\';')
      ..writeln()
      ..write('const Map<String, String> ${parts[0]}${ReCase(parts[1]).pascalCase} = {')
      ..writeln();

    // 添加所有键，包括可能缺失的键（使用空字符串作为默认值）
    for (final key in allKeys) {
      final camelCase = key.camelCase;
      final value = map[key] ?? ''; // 处理缺失的翻译键

      // 使用三引号包裹内容，避免引号转义问题
      buffer.writeln('  LanKeys.$camelCase: \'\'\'$value\'\'\',');
    }

    buffer.writeln('};');

    File('${outputDir.path}/lan_${lang.toLowerCase()}.dart').writeAsStringSync(buffer.toString());
  }
}
